//
//  YCSideMenuFrame.m
//  DemoSideMenu
//
//  Created by tangkexiong on 16/3/9.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCSideMenuFrame.h"

#import "YCSideMenuLeftMenuViewController.h"

#define kMenuTransformScale CATransform3DMakeScale(0.9, 0.9, 0.9)
#define kMenuLayerInitialOpacity 0.4f

typedef NS_ENUM(NSInteger, YCSlideMenuStatus) {
    YCSlideMenuStatusClosed         = 0,
    YCSlideMenuStatusLeftOpened     = 1
};

@interface YCSideMenuFrame ()<UIGestureRecognizerDelegate> {
    UIControl *_darknessView;
    YCSlideMenuStatus _status;
    CGFloat _maxWithOfLeftMenu;
    
    YCSideMenuLeftMenuViewController *_leftMenu;
    UINavigationController *_naviVC;
}

@end

@implementation YCSideMenuFrame

#pragma mark - UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _status = YCSlideMenuStatusClosed;
    _maxWithOfLeftMenu = [self widthOfLeftMenu];
    
    [self _configView];
}

- (void)_configView {
    self.view.backgroundColor = [UIColor blackColor];
    // 设置侧边栏
    _leftMenu = [self leftMenu];
    if (_leftMenu) {
        _leftMenu.menuFrame = self;
        
        _leftMenu.view.layer.transform = kMenuTransformScale;
        _leftMenu.view.layer.opacity = kMenuLayerInitialOpacity;
        
        [self addChildViewController:_leftMenu];
        [self.view addSubview:_leftMenu.view];
    }
    // 设置视图结构
    UIViewController *vc = [self homeContent];
    if (vc) {
        _naviVC = [[UINavigationController alloc] initWithRootViewController:vc];

        [self addChildViewController:_naviVC];
        [self.view addSubview:_naviVC.view];
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
        panGesture.delegate = self;
        [_naviVC.topViewController.view addGestureRecognizer:panGesture];
        
        UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self configLeftMenuButton:leftBtn];
        [leftBtn addTarget:self action:@selector(leftMenuBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        _naviVC.topViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    }
    // 设置半透明视图
    _darknessView = [[UIControl alloc] initWithFrame:CGRectZero];
    _darknessView.backgroundColor = [UIColor blackColor];
    [_darknessView addTarget:self action:@selector(darknessViewClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [_darknessView addGestureRecognizer:panGesture];
}

#pragma mark - Config 

- (YCSideMenuLeftMenuViewController *)leftMenu {
    return nil;
}

- (UIViewController *)homeContent {
    return nil;
}

- (CGFloat)widthOfLeftMenu {
    return 200.f;
}

- (CGFloat)maxDarknessWhileLeftMenu {
    return 0.5f;
}

- (void)configLeftMenuButton:(UIButton *)btn {
    
}

#pragma mark - UIGesture

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return NO;
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture {
    // 计算距离左侧的距离
    CGPoint point = [gesture locationInView:self.view];
    CGFloat leftMargin = point.x;
    if (leftMargin < 0) {
        leftMargin = 0;
    }
    if (leftMargin > _maxWithOfLeftMenu) {
        leftMargin = _maxWithOfLeftMenu;
    }

    if (gesture.state == UIGestureRecognizerStateBegan) {
        if (_status == YCSlideMenuStatusClosed) {
            _darknessView.alpha = 0;
            _darknessView.frame = CGRectMake(0, 0, _naviVC.view.frame.size.width, _naviVC.view.frame.size.height);
            [_naviVC.view addSubview:_darknessView];
            [_naviVC.view bringSubviewToFront:_darknessView];
            
            _darknessView.userInteractionEnabled = NO;
            _naviVC.topViewController.view.userInteractionEnabled = YES;
            
            _leftMenu.view.frame = CGRectMake(0, 0, _maxWithOfLeftMenu, [UIScreen mainScreen].bounds.size.height);
            [_leftMenu viewWillAppear:YES];
        } else if (_status == YCSlideMenuStatusLeftOpened) {
            _darknessView.userInteractionEnabled = YES;
            _naviVC.topViewController.view.userInteractionEnabled = NO;
            
            [_leftMenu viewWillDisappear:YES];
        }
    } else if (gesture.state==UIGestureRecognizerStateCancelled || gesture.state==UIGestureRecognizerStateEnded) {
        if (leftMargin < _maxWithOfLeftMenu/2.0) {
            [self closeLeftMenu];
        } else {
            [self openLeftMenu];
        }
    } else {
        CGRect naviVCRect = _naviVC.view.frame;
        naviVCRect.origin.x = leftMargin;
        _naviVC.view.frame = naviVCRect;
        
        CGFloat alpha = fabs(leftMargin / _maxWithOfLeftMenu * [self maxDarknessWhileLeftMenu]);
        _darknessView.alpha = alpha;
        
        float cx = 0;
        float cy = 0;
        float cz = 0;
        float opacity = 0;
        cx = kMenuTransformScale.m11 + (leftMargin / _maxWithOfLeftMenu) * (1.0 - kMenuTransformScale.m11);
        cy = kMenuTransformScale.m22 + (leftMargin / _maxWithOfLeftMenu) * (1.0 - kMenuTransformScale.m22);
        cz = kMenuTransformScale.m33 + (leftMargin / _maxWithOfLeftMenu) * (1.0 - kMenuTransformScale.m33);
        opacity = kMenuLayerInitialOpacity + (leftMargin / _maxWithOfLeftMenu) * (1.0 - kMenuLayerInitialOpacity);
        _leftMenu.view.layer.transform = CATransform3DMakeScale(cx, cy, cz);
        _leftMenu.view.layer.opacity = opacity;
    }
}

#pragma mark - IBAction

- (void)darknessViewClicked:(UIControl *)view {
    [_leftMenu viewWillDisappear:YES];
    
    [self closeLeftMenu];
}

#pragma mark - Control

- (void)closeLeftMenu {
    CGRect frame = _naviVC.view.frame;
    frame.origin.x = 0;
    
    CGFloat duration = _naviVC.view.frame.origin.x / _maxWithOfLeftMenu * 0.3f;
    
    [UIView animateWithDuration:duration animations:^{
        _naviVC.view.frame = frame;
        
        _leftMenu.view.layer.transform = kMenuTransformScale;
        _leftMenu.view.layer.opacity = kMenuLayerInitialOpacity;
        
        _darknessView.alpha = 0;
    } completion:^(BOOL finished) {
        [_darknessView removeFromSuperview];
        
        _status = YCSlideMenuStatusClosed;
        
        _darknessView.userInteractionEnabled = NO;
        _naviVC.topViewController.view.userInteractionEnabled = YES;
    } ];
}

- (void)openLeftMenu {
    CGFloat alpha = fabs(_naviVC.view.frame.origin.x / _maxWithOfLeftMenu * [self maxDarknessWhileLeftMenu]);
    if (alpha > [self maxDarknessWhileLeftMenu]) {
        alpha = [self maxDarknessWhileLeftMenu];
    }
    _darknessView.alpha = alpha;
    _darknessView.frame = CGRectMake(0, 0, _naviVC.view.frame.size.width, _naviVC.view.frame.size.height);
    [_naviVC.view addSubview:_darknessView];
    
    CGRect frame = _naviVC.view.frame;
    frame.origin.x = _maxWithOfLeftMenu;
    
    CGFloat duration = (_maxWithOfLeftMenu - _naviVC.view.frame.origin.x) / _maxWithOfLeftMenu * 0.3f;
    
    [UIView animateWithDuration:duration animations:^{
        _naviVC.view.frame = frame;
        
        _leftMenu.view.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1.0);
        _leftMenu.view.layer.opacity = 1.0f;
        _leftMenu.view.frame = CGRectMake(0, 0, _maxWithOfLeftMenu, [UIScreen mainScreen].bounds.size.height);
        
        _darknessView.alpha = [self maxDarknessWhileLeftMenu];
    } completion:^(BOOL finished) {
        _status = YCSlideMenuStatusLeftOpened;
        
        _darknessView.userInteractionEnabled = YES;
        _naviVC.topViewController.view.userInteractionEnabled = NO;
    }];
}

#pragma mark - IBAction

- (void)leftMenuBtnClicked:(id)sender {

}

#pragma mark - Method Public

- (void)switchToVC:(UIViewController *)vc {
    [self closeLeftMenu];
    
    if ([_naviVC.viewControllers containsObject:vc]) {
        [_naviVC popToViewController:vc animated:YES];
    } else {
        [_naviVC pushViewController:vc animated:YES];
    }
}

@end
